package com.ruoyi.api.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.api.service.InterceptUtilService;
import com.ruoyi.api.service.InventoryService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.WXShiroUtils;
import com.ruoyi.company.domain.*;
import com.ruoyi.company.service.*;
import com.ruoyi.company.utils.Util;
import com.ruoyi.procurement.domain.ProcurementModel;
import com.ruoyi.procurement.domain.ProcurementOrder;
import com.ruoyi.procurement.service.ProcurementServer;
import com.ruoyi.product.domain.Product;
import com.ruoyi.product.domain.ProductModel;
import com.ruoyi.product.mapper.ProductMapper;
import com.ruoyi.product.service.ProductServer;
import com.ruoyi.productProof.domain.ProductProof;
import com.ruoyi.productProof.service.ProductProofService;
import com.ruoyi.purchase.service.PurchaseOrderService;
import com.ruoyi.sale.domain.SaleGoodsModel;
import com.ruoyi.sale.domain.SaleGoodsOrder;
import com.ruoyi.sale.domain.SaleorderOrder;
import com.ruoyi.sale.service.ISaleGoodsService;
import com.ruoyi.sale.service.ISaleorderService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.warehousing.domain.Warehousing;
import com.ruoyi.warehousing.service.WarehousingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.ruoyi.common.core.domain.AjaxResult.Type.OTHER;

/**
 * 采购入库订单管理 PDA端
 */
@Controller
@RequestMapping("/api/business/selectPro")
public class SelectProcurementController extends BaseController {
    @Autowired
    ICompanyLinkmanServer iCompanyLinkmanServer;
    @Autowired
    ISaleorderService iSaleorderService;
    @Autowired
    ICompanyInvoiceService iCompanyInvoiceService;
    @Autowired
    ICompanyMyLinkmanServer iCompanyMyLinkmanServer;
    @Autowired
    InventoryService inventoryService;
    @Autowired
    ICompanyServer iCompanyServer;
    @Autowired
    ProductServer productServer;
    @Autowired
    InterceptUtilService interceptUtilService;
    @Autowired
    WarehousingService warehousingService;
    @Autowired
    ProductProofService proofService;
    @Autowired
    ISaleGoodsService saleGoodsService;
    @Autowired
    ICompanyOtherServer iCompanyOtherServer;
    @Autowired
    ISysDeptService iSysDeptService;
    @Autowired
    private ProcurementServer procurementServer;
    @Autowired
    private PurchaseOrderService purchaseOrderService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ICompanyInvoiceService invoiceService;
    @Autowired
    private ISaleGoodsService iSaleGoodsService;

    @Autowired
    private ProductMapper productMapper;

    //时间类型转换，将string转换为date
    public static Date generateDate(String str) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");//设置时间格式
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");//设置时间格式
        Date ts = new Date();//创建Date对象

        String substring = sdf.format(ts).substring(0, 2);
        String date = substring + str;
        try {
            ts = sdf.parse(str);//转换为Date类型 这里要抛一个异常
//            ts = sdf.parse(date);//转换为Date类型 这里要抛一个异常
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ts;
    }


//    /**
//     * 截取扫描的型号唯一码 采购入库
//     */
//    @PostMapping("/interceptStr")
//    @ResponseBody
//    public AjaxResult interceptStr(String barCode, String modelCode, Long companyId, Long saleGoodsId) {
//        String intercept = interceptUtilService.intercept(barCode);
//        if (intercept.equals("0") || intercept.equals("")) {
//            return new AjaxResult(OTHER, "AI码扫描失败，请重新扫描");
//        }
//        ProductModel productModel = new ProductModel();
//
//        if (modelCode == null || modelCode.equals("") || modelCode.equals("undefined")) {
//            modelCode = intercept;
//        } else {
//            if (!modelCode.equals(intercept)) {
//                return new AjaxResult(OTHER, "产品规格的型号唯一码不符，请扫描同一款的产品");
//            }
//        }
//
//        if (companyId == null) {
//            companyId = WXShiroUtils.getSysUser().getCompanyId();
//        }
//
//        productModel = productServer.selectProductByModelCode(companyId, modelCode);
//
//        if (productModel != null) {
//            Long productId = productModel.getProductId();
//            String productType = productModel.getProductType();
//            Long modelNo = productModel.getModelNo();
//            Warehousing warehousing = new Warehousing();
//            warehousing.setProductId(productId);
//            warehousing.setProductType(productType);
//            warehousing.setModelCode(modelCode);
//            warehousing.setModelNo(modelNo);
//            warehousing.setProductName(productModel.getProductName());
//            //定义存储截取后的字符串
//            List<Map<String, String>> intercept1 = null;
//            try {
//                intercept1 = interceptUtilService.intercept(productId, barCode, companyId);
//            } catch (Exception e) {
//                return new AjaxResult(OTHER, e.getMessage());
//            }
//            List<Warehousing> warehousings = new ArrayList<>();
//            if (intercept1.size() != 0) {
//                //定义变量，用于判断是否截取全部的字符串
//                int i = 0;
//                for (Map<String, String> map : intercept1) {
//                    if (map.get("10") != null && map.get("17") != null) {
//                        warehousing = new Warehousing();
//                        i++;
//                        //产品批号
//                        String s = map.get("10");
//                        //失效日期
//                        String effectiveDate = map.get("17");
//                        //生产日期
//                        String productDate = map.get("11");
//                        warehousing.setProductId(productId);
//                        warehousing.setProductName(productModel.getProductName());
//                        warehousing.setDeptId(companyId);
//                        warehousing.setBatch(s);
//                        warehousing.setModelCode(modelCode);
//                        warehousing.setModelNo(modelNo);
//                        warehousing.setProductType(productType);
//                        Date effectiveDates = generateDate(effectiveDate);
//                        Date productDates = null;
//                        //查询产品的生产时间，截取到则直接放入map中，否，则通过查询产品的生产日期计算规则生成生产日期
//                        Map maps = new HashMap<String, Object>();
//                        if (productDate == null || ("").equals(productId)) {
//                            productDate = productServer.calculateDate(effectiveDate, productId);
//                            productDates = generateDate(productDate);
//                        }
//                        maps.put("productionDate", productDates);
//                        maps.put("productId", productId);
////                        maps.put("deptId", WXShiroUtils.getSysUser().getCompanyId());
//                        maps.put("deptId", companyId);
//
//                        //判断是否为销货单入库，为对方公司的产品信息
//                        if (saleGoodsId != null) {
//                            //定义新的产品销货单的查询，查询销货单的信息
//                            Map<String, Object> map1 = new HashMap<>();
//                            map1.put("saleGoodsId", saleGoodsId);
//                            map1.put("batch", s);
//                            SaleGoodsModel saleGoodsModel = saleGoodsService.selectSaleModelByMap(map1);
//                            if (saleGoodsModel != null) {
//                                //设置销货单入库的 在库数量 销货单数量 含税单价 函数总金额 税率
//                                warehousing.setWarehousingNum(saleGoodsModel.getWarehousingNum().intValue());
//                                warehousing.setNum(saleGoodsModel.getNum());
//                                warehousing.setTaxPrice(saleGoodsModel.getTaxPrice());
//                                warehousing.setPrice(saleGoodsModel.getPrice());
//                                warehousing.setTaxRate(saleGoodsModel.getTaxRate());
//                            } else {
//                                continue;
//                            }
//                        } else {
//                            warehousing.setWarehousingNum(0);
//                        }
//
//                        //设置 失效日期 生产日期
//                        warehousing.setEffectiveDate(effectiveDates);
//                        warehousing.setProductionDate(productDates);
//                        //查询产品的注册证信息
//                        ProductProof productProof = new ProductProof();
//                        if (maps.size() != 0) {
//                            productProof = proofService.selectProductProofByMap(maps);
//                        }
//                        if (productProof.getMedicalNumber() != null) {
//                            //设置 产品医疗器械注册证编号 产品注册的失效日期
//                            warehousing.setMedicalNumber(productProof.getMedicalNumber());
//                            warehousing.setMedicalEndTime(productProof.getMedicalEndTime());
//                            warehousings.add(warehousing);
//                        } else {
//                            warehousing.setMedicalNumber(null);
//                            warehousings.add(warehousing);
//                        }
//                    }
//                }
//                if (warehousings.size() != 0) {
//                    return AjaxResult.success("扫描成功", warehousings);
//                } else {
//                    if (i == 0) {
//                        return new AjaxResult(AjaxResult.Type.SPLICE, "扫描不全，请继续扫描", warehousing);
//                    } else {
//                        return new AjaxResult(OTHER, "扫描错误，清空扫描信息");
//                    }
//                }
//            } else {
//                return new AjaxResult(OTHER, "该产品型号未找到，清空扫描信息");
//            }
//        } else {
//            return new AjaxResult(OTHER, "该产品型号未找到");
//        }
//    }

    /**
     * 查询采购订单入库信息列表
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ProcurementOrder procurement) {
        startPage();
        procurement.setDeptId(SecurityUtils.getLoginUser().getCompanyId());
//        procurement.setDeptId(101L);
        List<ProcurementOrder> list = procurementServer.selectProcurementList(procurement);
        return getDataTable(list);
    }

    /**
     * 截取扫描的型号唯一码 采购入库
     */
    @PostMapping("/interceptStr")
    @ResponseBody
    public AjaxResult interceptStr(String[] barCode, String modelCode, Long companyId, Long saleGoodsId) {
        String intercept = interceptUtilService.intercept(barCode);
        if (intercept.equals("0") || intercept.equals("")) {
            return new AjaxResult(OTHER, "AI码扫描失败，请重新扫描");
        }
        ProductModel productModel = new ProductModel();

        if (modelCode == null || modelCode.equals("") || modelCode.equals("undefined")) {
            modelCode = intercept;
        } else {
            if (!modelCode.equals(intercept)) {
                return new AjaxResult(OTHER, "产品规格的型号唯一码不符，请扫描同一款的产品");
            }
        }

        if (companyId == null) {
            companyId = SecurityUtils.getLoginUser().getCompanyId();
//            companyId = 101L;
        }
        productModel = productServer.selectProductByModelCode(companyId, modelCode);
        if (productModel != null) {
            Long productId = productModel.getProductId();
            String productType = productModel.getProductType();
            Long modelNo = productModel.getModelNo();
            Warehousing warehousing = new Warehousing();
            warehousing.setProductId(productId);
            warehousing.setProductType(productType);
            warehousing.setModelCode(modelCode);
            warehousing.setModelNo(modelNo);
            warehousing.setProductName(productModel.getProductName());
            //定义存储截取后的字符串
            List<Map<String, String>> intercept1 = null;
            try {
                intercept1 = interceptUtilService.intercept(productId, barCode, companyId, modelCode);
            } catch (Exception e) {
                return new AjaxResult(OTHER, e.getMessage());
            }
            List<Warehousing> warehousings = new ArrayList<>();
            if (intercept1.size() != 0) {
                //定义变量，用于判断是否截取全部的字符串
                int i = 0;
                for (Map<String, String> map : intercept1) {
                    if (map.get("10") != null && map.get("17") != null) {
                        warehousing = new Warehousing();
                        i++;
                        //产品批号
                        String s = map.get("10");
                        //失效日期
                        String effectiveDate = map.get("17");
                        //生产日期
//                        String productDate = map.get("11");
                        String productDate = "";
                        warehousing.setUnit(productModel.getUnit());
                        warehousing.setProductId(productId);
                        warehousing.setProductName(productModel.getProductName());
                        warehousing.setDeptId(companyId);
                        warehousing.setBatch(s);
                        warehousing.setModelCode(modelCode);
                        warehousing.setModelNo(modelNo);
                        warehousing.setFactor(productModel.getFactor());
                        warehousing.setProductType(productType);
                        warehousing.setTaxRate(iCompanyServer.selectByCompanyId(companyId).getTaxRate());
                        Date effectiveDates = generateDate(effectiveDate);
                        Date productDates = null;
                        //查询产品的生产时间，截取到则直接放入map中，否，则通过查询产品的生产日期计算规则生成生产日期
                        Map maps = new HashMap<String, Object>();
                        if (productDate == null || !("").equals(productId)) {
                            productDate = productServer.calculateDate(effectiveDate, productId);
                            productDates = generateDate(productDate);
                        } else {
                            productDates = generateDate(productDate);
                        }
                        maps.put("productionDate", productDates);
                        maps.put("productId", productId);
//                        maps.put("deptId", WXShiroUtils.getSysUser().getCompanyId());
                        maps.put("deptId", companyId);

                        //判断是否为销货单入库，为对方公司的产品信息
                        if (saleGoodsId != null) {
                            //定义新的产品销货单的查询，查询销货单的信息
                            Map<String, Object> map1 = new HashMap<>();
                            map1.put("saleGoodsId", saleGoodsId);
                            map1.put("batch", s);
                            map1.put("modelCode", modelCode);
                            SaleGoodsModel saleGoodsModel = saleGoodsService.selectSaleModelByMap(map1);
                            if (saleGoodsModel.getSaleGoodsId() == null) {
                                continue;
//                                return new AjaxResult(OTHER, "该产品型号未在销货单中找到，清空扫描信息");
                            } else {
                                warehousing.setWarehousingNum(saleGoodsModel.getWarehousingNum().intValue());
                                warehousing.setNum(saleGoodsModel.getNum());
                                warehousing.setTaxPrice(saleGoodsModel.getTaxPrice());
                                warehousing.setPrice(saleGoodsModel.getPrice());
                                warehousing.setTaxRate(saleGoodsModel.getTaxRate());
                            }

//                            if (saleGoodsModel != null) {
//                                //设置销货单入库的 在库数量 销货单数量 含税单价 函数总金额 税率
//                                warehousing.setWarehousingNum(saleGoodsModel.getWarehousingNum().intValue());
//                                warehousing.setNum(saleGoodsModel.getNum());
//                                warehousing.setTaxPrice(saleGoodsModel.getTaxPrice());
//                                warehousing.setPrice(saleGoodsModel.getPrice());
//                                warehousing.setTaxRate(saleGoodsModel.getTaxRate());
//                            } else {
//                                continue;
//                            }
                        } else {
                            warehousing.setWarehousingNum(0);
                        }

                        //设置 失效日期 生产日期
                        warehousing.setEffectiveDate(effectiveDates);
                        warehousing.setProductionDate(productDates);
                        //查询产品的注册证信息
                        Product product = new Product();
                        if (maps.size() != 0) {
                            product = productMapper.selectMedicalNumer(productModel.getSelectId());
                        }
                        if (product.getMedicalNumber() != null) {
                            //设置 产品医疗器械注册证编号 产品注册的失效日期
                            warehousing.setMedicalNumber(product.getMedicalNumber());
                            warehousing.setMedicalEndTime(product.getEndTime());
                            warehousings.add(warehousing);
                        } else {
                            warehousing.setMedicalNumber(null);
                            warehousing.setMedicalEndTime(null);
                            warehousings.add(warehousing);
                        }
                    }
                }
                if (warehousings.size() != 0) {
                    return AjaxResult.success("扫描成功", warehousings);
                } else {
                    if (i == 0) {
                        return new AjaxResult(201, "扫描不全，请继续扫描", warehousing);
                    } else {
                        return new AjaxResult(OTHER, "扫描错误，清空扫描信息");
                    }
                }
            } else {
                return new AjaxResult(OTHER, "该产品型号未找到，清空扫描信息");
            }
        } else {
            return new AjaxResult(OTHER, "该产品型号未找到");
        }
    }

    /**
     * 加载采购订单入库信息
     */
    @PostMapping("/addPro")
    @ResponseBody
    public AjaxResult addPro() {
        Map<String, Object> map = new HashMap<>();
        //使用SimpleDateFormat的parse()方法生成Date
        SimpleDateFormat a = new SimpleDateFormat("yyyy-MM-dd");
        String format = "";
        Date dates = null;
        try {
//            String format = a.format(new Date());
            format = a.format(new Date());
            map.put("dates", format);
//            Date dates = a.parse(format);
            dates = a.parse(format);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //生成的订单编号
        String s = purchaseOrderService.orderNum(dates, 6);
        if (s.equals("0")) {
            return AjaxResult.error("请先设置前缀");
        }
        map.put("procurementNum", s);
        //获取当前登录的公司主键
        Long companyId = SecurityUtils.getLoginUser().getCompanyId();
//        Long companyId = 101L;
        map.put("supplier", userService.selectSupplierById(companyId));
        map.put("user", userService.selectSalesmanList(companyId));
        CompanyInvoice companyInvoice = invoiceService.selectByCompanyId(companyId);
        if (companyInvoice != null) {
            map.put("taxRate", companyInvoice.getTaxRate());
        } else {
            map.put("taxRate", 0);
        }
        return AjaxResult.success(map);
    }

    /**
     * 根据companyId 查询 公司名称
     */
    @PostMapping("/selectDeptNameById")
    @ResponseBody
    public AjaxResult selectDeptNameById() {
        Long companyId = SecurityUtils.getLoginUser().getCompanyId();
        Map<String, Object> map = new HashMap<>();
        map.put("supplier", userService.selectSupplierById(companyId));
        map.put("user", userService.selectSalesmanList(companyId));
        map.put("taxRate", invoiceService.selectByCompanyId(companyId));
        return AjaxResult.success(map);
    }

    /**
     * 生成采购入库订单编号
     */
    @ResponseBody
    @PostMapping("/orderNum")
    public AjaxResult orderNum(Date date, int type) {
        Map<String, Object> map = new HashMap<>();
        String orderNum = purchaseOrderService.orderNum(date, type);
        if (orderNum.equals(0)) {
            return AjaxResult.error("请先设置订单编号前缀！");
        }
        map.put("orderNum", orderNum);
        return AjaxResult.success(map);
    }

    /**
     * 查询供应商的绑定业务员
     */
    @PostMapping("/selectUser")
    @ResponseBody
    public AjaxResult selectUser(Long companyId) {
//    @PostMapping("/selectUser/{companyId}")
//    @ResponseBody
//    public AjaxResult selectUser(@PathVariable("companyId") Long companyId) {
        Map<String, Object> map = new HashMap<>();
        map.put("deptId", SecurityUtils.getLoginUser().getCompanyId());
        map.put("companyId", companyId);
        CompanyOther companyOther = iCompanyOtherServer.selectByCompanyIdAndDeptId(map);
        if (companyOther != null) {
            return AjaxResult.success(companyOther);
        } else {
            return AjaxResult.error("该公司没有合作单位请设置负责人信息");
        }
    }

    /**
     * 查询产品型号规格信息
     *
     * @param product 查询条件
     * @return 结果
     */
    @PostMapping("/selectProductLists")
    @ResponseBody
    public TableDataInfo selectProductLists(Product product) {
        startPage();
        product.setDeptId(SecurityUtils.getLoginUser().getCompanyId());
//        product.setDeptId(101L);
        return getDataTable2(procurementServer.selectProductLists(product));
    }

    /**
     * 重写分页信息
     *
     * @param list 列表
     * @return 结果
     */
    protected TableDataInfo getDataTable2(List<?> list) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(list);
        rspData.setTotal(list.size());
        return rspData;
    }

    /**
     * 选择销货订单列表 post
     */
    @PostMapping("/selectSalegoodsList")
    @ResponseBody
    public TableDataInfo showlist(SaleGoodsOrder saleGoodsOrder) {
        startPage();
        saleGoodsOrder.setCustomerId(SecurityUtils.getLoginUser().getCompanyId());
//        saleGoodsOrder.setCustomerId(101L);
        saleGoodsOrder.setSaleGoodsStatus("1");
        saleGoodsOrder.setIsWarehousingOrder(0);
        List<SaleGoodsOrder> list = iSaleGoodsService.selectSaleGoodsListes(saleGoodsOrder);
        return getDataTable(list);
    }

    /**
     * 新增保存入库信息
     */
    @Log(title = "新增保存", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    @Transactional
    public AjaxResult addSave(@RequestBody ProcurementOrder procurementOrder) {
        List<ProcurementModel> procurementModelList = procurementOrder.getProcurementModelList();
        for (ProcurementModel procurementModel : procurementModelList) {
            if (procurementModel.getMedicalNumber() == null) {
                return AjaxResult.error("批次" + procurementModel.getBatch() + "的生产日期匹配不到符合的医疗器械注册证，请重新选择生产日期！");
            }
        }

        String procurementWarehousingName = procurementOrder.getProcurementWarehousingName();
        Long saleGoodsId = procurementOrder.getSaleGoodsId();
        Long companyId = SecurityUtils.getLoginUser().getCompanyId();
        HashMap<String, Object> map = new HashMap<>();
        map.put("saleGoodsId", saleGoodsId);
        map.put("procurementWarehousingName", procurementWarehousingName);
        map.put("companyId", companyId);
        ProcurementOrder procurementOrder1 = procurementServer.selectProcurementByMap(map);
        if (procurementOrder1 != null) {
            //使用SimpleDateFormat的parse()方法生成Date
            SimpleDateFormat a = new SimpleDateFormat("yyyy-MM-dd");
            Date dates = null;
            try {
//              dates = a.parse(a.format(new Date()));
                dates = a.parse(a.format(procurementOrder.getProcurementWarehousingDate()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            String s = purchaseOrderService.orderNum(dates, 6);
            procurementOrder.setProcurementWarehousingName(s);
        }

        return AjaxResult.success(procurementServer.insertProcurementOrderPDA(procurementOrder));
//        return AjaxResult.error("这是错误测试");
    }

    /**
     * 查看入库订单
     */
    @PostMapping("/look")
    @ResponseBody
    public AjaxResult look(Long procurementWarehousingId) {
        Map<String, Object> map = new HashMap<>();
        ProcurementOrder procurementOrders = new ProcurementOrder();
        procurementOrders.setProcurementWarehousingId(procurementWarehousingId);
        ProcurementOrder procurementOrder1 = procurementServer.selectProcurementBy(procurementOrders);
        List<ProcurementModel> procurementModels = procurementServer.selectProcurementModelById(procurementWarehousingId);
        if (procurementModels.size() != 0) {
            map.put("procurementOrder", procurementOrder1);
        } else {
            procurementOrder1.setProcurementModelList(procurementModels);
            map.put("procurementOrder", procurementOrder1);
        }
        return AjaxResult.success(map);
    }

    /**
     * 查看销货单
     */
    @PostMapping("/lookOrder")
    @ResponseBody
    public AjaxResult lookOrder(Long saleGoodsId) {
        Map<String, Object> map = new HashMap<>();
        map.put("saleGoodsId", saleGoodsId);
        SaleGoodsOrder saleGoods = saleGoodsService.selectSaleGoodsByMap(map);
        return AjaxResult.success(saleGoods);
    }

    /**
     * 查询产品注册证
     *
     * @param productionDate 失效期
     * @param productId      产品主键
     * @param deptId         公司主键
     * @return 结果
     */
    @PostMapping("/selectProductProof")
    @ResponseBody
    public AjaxResult selectProductProof(Date productionDate, Long productId, Long deptId) {
        Map map = new HashMap<String, Object>();
        if (deptId == null || ("").equals(deptId)) {
            deptId = SecurityUtils.getLoginUser().getCompanyId();
//            deptId = 101L;
        }
        if (productionDate == null || ("").equals(productId) || productId == null) {
            return new AjaxResult(OTHER, "当前批次的生产日期匹配不到符合的医疗器械注册证");
        }
        map.put("productionDate", productionDate);
        map.put("productId", productId);
        map.put("deptId", deptId);
//        if (productionDate != null && !("").equals(productId) && productId != null) {
//            map.put("productionDate", productionDate);
//            map.put("productId", productId);
//            map.put("deptId", deptId);
//        }
        ProductProof productProof = proofService.selectProductProofByMap(map);
        if (productProof.getMedicalNumber() == null) {
            return new AjaxResult(OTHER, "当前批次的生产日期匹配不到符合的医疗器械注册证");
        }
        return AjaxResult.success("该产品的医疗器械注册", productProof);
    }

    @PostMapping("/dataIntoContract")
    @ResponseBody
    public JSONObject dataIntoContract(Long saleorderId, ServletRequest request) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("saleorderId", saleorderId);
        hashMap.put("deptId", SecurityUtils.getLoginUser().getCompanyId());
//        SaleorderOrder saleorderOrder = iSaleorderService.selectSaleorderById(hashMap);
        SaleorderOrder saleorderOrder = iSaleorderService.selectSaleorderByIdMap(hashMap);
        Company company = iCompanyServer.selectByCompanyId(saleorderOrder.getDeptId());

        //需方 信息;
        Company demanderData = iCompanyServer.selectByCompanyId(saleorderOrder.getCompanyId());
        CompanyInvoice demanderInvoiceData = iCompanyInvoiceService.selectByCompanyId(saleorderOrder.getCompanyId());
        Map<String, Object> linkMap = new HashMap<>();
        linkMap.put("deptId", ShiroUtils.getSysUser().getCompanyId());
        linkMap.put("companyId", saleorderOrder.getCompanyId());
        List<CompanyLinkman> companyLinkmen = iCompanyLinkmanServer.selectLinkman(linkMap);
        CompanyLinkman companyLinkman = companyLinkmen.get(0);

        //供方 信息;
        Company purchaseData = iCompanyServer.selectByCompanyId(saleorderOrder.getDeptId());
        CompanyInvoice purchaseInvoiceData = iCompanyInvoiceService.selectByCompanyId(saleorderOrder.getDeptId());

        Map<String, Object> myLinkMap = new HashMap<>();
        myLinkMap.put("deptId", ShiroUtils.getSysUser().getCompanyId());
        List<CompanyMyLinkman> companyMyLinkmen = iCompanyMyLinkmanServer.selectLinkman(linkMap);
        CompanyMyLinkman companyMyLinkman = new CompanyMyLinkman();
        if (companyMyLinkmen.size() != 0) {
            companyMyLinkman = companyMyLinkmen.get(0);
        }
        JSONObject jsonObject = new JSONObject();
        //合同编号 是销售订单的编号
        jsonObject.put("contractNo", saleorderOrder.getSaleorderNum());
        //供方
        jsonObject.put("purchaseName", iSysDeptService.selectDeptById(saleorderOrder.getDeptId()).getDeptName());
        //签订日期 contractDate
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        jsonObject.put("contractDate", fmt.format(saleorderOrder.getSaleorderDate()));
        //需方
        jsonObject.put("demander", iSysDeptService.selectDeptById(saleorderOrder.getCompanyId()).getDeptName());
        //签订地点
        Map map = new HashMap();
        map.put("deptId", saleorderOrder.getDeptId());
        map.put("companyId", saleorderOrder.getCompanyId());
        map.put("gradeStatus", "02");
        CompanyOther companyOther = iCompanyOtherServer.selectByCompanyIdAndDeptId(map);
        if (companyOther == null) {
            new AjaxResult(AjaxResult.Type.ERROR, "您还没有建立与该合作单位的合作关系，请在基础信息-合作单位管理菜单模块建立合作关系。");
            throw new RuntimeException("您还没有建立与该合作单位的合作关系，请在基础信息-合作单位管理菜单模块建立合作关系。");
        }
        jsonObject.put("contractAddress", company.getCity());
        //销售订单产品
        JSONArray jsonArrayModel = new JSONArray();
        for (int i = 0; i < saleorderOrder.getSaleorderModels().size(); i++) {
            jsonArrayModel.add(saleorderOrder.getSaleorderModels().get(i));
        }
        jsonObject.put("models", jsonArrayModel);
        //总数量
        int totalNum = 0;
        for (int i = 0; i < saleorderOrder.getSaleorderModels().size(); i++) {
            totalNum += saleorderOrder.getSaleorderModels().get(i).getNum();
        }
        jsonObject.put("totalNum", totalNum);
        //总金额
        jsonObject.put("totalMoney", saleorderOrder.getSaleorderTaxamount());
        //合计人民币
        BigDecimal taxamount = saleorderOrder.getSaleorderTaxamount();
        double saleorderTaxamount = taxamount.doubleValue();
//        jsonObject.put("upperMoney", upperCase(saleorderTaxamount));
        jsonObject.put("upperMoney", Util.upperCases(saleorderTaxamount));
        //合同约定项
        JSONArray jsonContractTerms = new JSONArray();
        String contractTerms = companyOther.getContractTerms();
        //根据回车进行分割
        String[] contractTermsArr = new String[]{};
        if (!"".equals(contractTerms) && contractTerms != null) {
            contractTermsArr = contractTerms.split("\\r?\\n");
        }
        for (int i = 0; i < contractTermsArr.length; i++) {
            String str = contractTermsArr[i];
            jsonContractTerms.add(str);
        }
        jsonObject.put("contractTerms", jsonContractTerms);

        //供货单位
        //地址
        jsonObject.put("purchaseAddress", purchaseData.getProvince() + purchaseData.getCity() + purchaseData.getOtherCorporateAddress());

        //印章
        String purSeal = "";
        if (purchaseData.getElectronicSealUrl() != null && !"".equals(purchaseData.getElectronicSealUrl())) {
            purSeal = purchaseData.getElectronicSealUrl();
            purSeal = purSeal.split("/profile/upload")[1];
            try {
                purSeal = Util.encodeToString(RuoYiConfig.getUploadPath() + purSeal);
            } catch (IOException e) {
                e.printStackTrace();
            }
//            try {
//                purSeal = Util.encodeToString(RuoYiConfig.getDownloadPath() + purSeal);
//                String downloadPath = RuoYiConfig.getDownloadPath();
//                File file = new File(downloadPath);
//                if (!file.exists()) {
//                    file.mkdir();
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
        } else {
//            if (purchaseData.getSealUrl() != null && !"".equals(purchaseData.getSealUrl())) {
//                purSeal = purchaseData.getSealUrl();
//            } else {
////                //生成电子印章到服务器
////                //自动生成一个印章 上传到服务器上
////                String socialCreditCode = purchaseData.getSocialCreditCode();
////                String imgname = socialCreditCode + ".png";
////                String downloadPath = RuoYiConfig.getDownloadPath();
////                File file = new File(downloadPath);
////                if (!file.exists()) {
////                    file.mkdir();
////                }
////                File pngfile = new File(downloadPath + "/seal");
////                if (!pngfile.isDirectory()) {
////                    pngfile.mkdir();
////                }
////                String path = downloadPath + "seal/" + imgname;
////                //生成 印章照片
////                try {
////                    SealUtils.toSeal(iSysDeptService.selectDeptById(purchaseData.getCompanyId()).getDeptName(), purchaseData.getSocialCreditCode(), path);
////                } catch (Exception e) {
////                    e.printStackTrace();
////                }
////                Company company2 = new Company();
////                company2.setSealUrl("/seal/" + imgname);
////                company2.setCompanyId(purchaseData.getCompanyId());
////                purSeal = "/seal/" + imgname;
////                //更新url
////                iCompanyServer.updateCompany(company2);
//            }
////            //将图片 转为64位 返回
////            try {
////                purSeal = Util.encodeToString(RuoYiConfig.getDownloadPath() + purSeal);
////            } catch (IOException e) {
////                e.printStackTrace();
////            }
        }

        if (!purSeal.equals("")) {
            jsonObject.put("purSeal", "data:image/jpg;base64," + purSeal);
        }

        //邮编

        //电话
//        jsonObject.put("purchasePhone", purchaseInvoiceData.getCorporateRegisterPhone());
        jsonObject.put("purchasePhone", companyMyLinkman.getPhoneNum());
        //统一社会信用代码
        jsonObject.put("purchaseSocialCreditCode", purchaseData.getSocialCreditCode());
        //开户
        jsonObject.put("purchaseBank", purchaseInvoiceData.getDepositBank());
        //账号
        jsonObject.put("purchaseBankNum", purchaseInvoiceData.getBankNumber());
        //签约代表
//        jsonObject.put("purchaseCustomerForStaff", purchaseData.getCorporateRepresentative());
        jsonObject.put("purchaseCustomerForStaff", companyMyLinkman.getName());

        //供货单位

        //地址
        jsonObject.put("demanderAddress", demanderData.getProvince() + demanderData.getCity() + demanderData.getOtherCorporateAddress());

        //印章
        String demanderSeal = "";
        if (demanderData.getElectronicSealUrl() != null && !"".equals(demanderData.getElectronicSealUrl())) {
            demanderSeal = demanderData.getElectronicSealUrl();
            demanderSeal = demanderSeal.split("/profile/upload")[1];
            try {
                demanderSeal = Util.encodeToString(RuoYiConfig.getUploadPath() + demanderSeal);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
//            if (demanderData.getSealUrl() != null && !"".equals(demanderData.getSealUrl())) {
//                demanderSeal = demanderData.getSealUrl();
//                try {
//                    demanderSeal = Util.encodeToString(RuoYiConfig.getDownloadPath() + demanderSeal);
//                    String downloadPath = RuoYiConfig.getDownloadPath();
//                    File file = new File(downloadPath);
//                    if (!file.exists()) {
//                        file.mkdir();
//                    }
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            } else {
////                //生成电子印章到服务器
////                //自动生成一个印章 上传到服务器上
////                String socialCreditCode = demanderData.getSocialCreditCode();
////                String imgname = socialCreditCode + ".png";
////                String downloadPath = RuoYiConfig.getDownloadPath();
////                File file = new File(downloadPath);
////                if (!file.exists()) {
////                    file.mkdir();
////                }
////
////                File pngfile = new File(downloadPath + "/seal");
////                if (!pngfile.exists()) {
////                    pngfile.mkdir();
////                }
////                String path = downloadPath + "seal/" + imgname;
////                //生成 印章照片
////                try {
////                    SealUtils.toSeal(iSysDeptService.selectDeptById(demanderData.getCompanyId()).getDeptName(), demanderData.getSocialCreditCode(), path);
////                } catch (Exception e) {
////                    e.printStackTrace();
////                }
////                Company company3 = new Company();
////                company3.setSealUrl("/seal/" + imgname);
////                company3.setCompanyId(demanderData.getCompanyId());
////                demanderSeal = "/seal/" + imgname;
////                //更新url
////                iCompanyServer.updateCompany(company3);
//            }
////            try {
////                demanderSeal = Util.encodeToString(RuoYiConfig.getDownloadPath() + demanderSeal);
////            } catch (IOException e) {
////                e.printStackTrace();
////            }
        }
        if (!demanderSeal.equals("")) {
            jsonObject.put("demanderSeal", "data:image/jpg;base64," + demanderSeal);
        }

        //邮编

        //电话
//        jsonObject.put("demanderPhone", demanderInvoiceData.getCorporateRegisterPhone());
        jsonObject.put("demanderPhone", companyLinkman.getPhoneNum());
        //统一社会信用代码
        jsonObject.put("demanderSocialCreditCode", demanderData.getSocialCreditCode());
        //开户
        jsonObject.put("demanderBank", demanderInvoiceData.getDepositBank());
        //账号
        jsonObject.put("demanderBankNum", demanderInvoiceData.getBankNumber());
        //签约代表
//        jsonObject.put("demanderCustomerForStaff", demanderData.getCorporateRepresentative());
        jsonObject.put("demanderCustomerForStaff", companyLinkman.getName());

        return jsonObject;
    }
}
